# 获取视频弹幕
import requests
import re
import pandas

# 1、模拟浏览器发起请求
    #request  地址：用户信息
url='https://api.bilibili.com/x/v2/dm/history?type=1&oid=210738676&date=2021-01-17'
    #发起请求 urllib requests（第三方库）
    #规定：状态码不是200 ，全为错
#response=requests.get(url)
#print(response.text)


# 2、获取响应内容
    #键值对通过字典{}进行存储
headers={
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
    "cookie": "_uuid=326F06D1-FE8D-9191-42CE-DD309D14353C67633infoc; buvid3=33D869DB-6F2F-4BB0-B607-1B7B34F07CFD53925infoc; sid=4lmxv7lu; rpdid=|(u)Y|l|uJRk0J'ulmJY|kRR|; dy_spec_agreed=1; LIVE_BUVID=AUTO2815973097085458; blackside_state=1; CURRENT_FNVAL=80; fingerprint=073aaf7f9d22ae55cfafd954c7f31b26; buivd_fp=33D869DB-6F2F-4BB0-B607-1B7B34F07CFD53925infoc; buvid_fp=33D869DB-6F2F-4BB0-B607-1B7B34F07CFD53925infoc; DedeUserID=26390853; DedeUserID__ckMd5=8d24b1d50476c5e5; SESSDATA=c6386003%2C1624877887%2Ca501d*c1; bili_jct=704cf795ee7a134f74dd244b80c5107d; fingerprint3=e2c8e8428b5dd20a53fb6c8510486617; fingerprint_s=a2d9b6e6406a1f7cdec43ec386e58281; buvid_fp_plain=33D869DB-6F2F-4BB0-B607-1B7B34F07CFD53925infoc; bfe_id=5112800f2e3d3cf17a473918472e345c; PVID=2"
}

data=requests.get(url,headers=headers)
data.encoding='utf-8'
#print(data.text)


# 3、解析内容（弹幕）
#<d p="93.67600,1,25,16777215,1610898305,0,866c00b3,43912334254538759">哈哈哈哈哈</d>
#解析内容的方法：bs4(第三方模块)、正则表达式、xpath
# python封装解析模块：re    findall('解析规则'，解析文件)
#正则表达式：.当前位置字符，* 0次或者多次匹配，?满足当前规则的前提下，尽可能少的匹配
DM=re.findall('<d p=".*?">(.*?)</d>',data.text)
#print(DM)


# 4、保存内容
#pandas   格式转化：DataFrame 保存内容: to_csv('保存位置'，‘保存的编码格式’)
test=pandas.DataFrame(data=DM)
#print(test)
test.to_csv('save/danmu.csv',encoding='utf-8')

